package com.weimob.mcloud.wechatwork.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weimob.arch.sub.env.application.annotation.SubEnvExposePoint;
import com.weimob.arch.sub.env.application.annotation.SubEnvTagExtractor;
import com.weimob.artemis.client.producer.ArtemisProducer;
import com.weimob.artemis.client.producer.config.ProducerConfig;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Create Time: 2021年01月19日 16:41
 *
 * @author maosheng.li
 **/
@Slf4j
@Component
public class ArtemisService {

    @Autowired
    private ArtemisProducer artemisProducer;

    public Boolean sendToArtemis(ArtemisBaseInfo artemisModel) {
        ProducerConfig producerConfig = ProducerConfig.builder().user(artemisModel.getProducer()).build();
        try {
            log.info("Send artemis message topic:{},message:{}", JSONObject.toJSONString(artemisModel.getTopic()), JSON.toJSONString(artemisModel.getEvent()));
            artemisProducer.send(producerConfig, artemisModel.getTopic(), JSON.toJSONString(artemisModel.getEvent()));
        } catch (Exception e) {
            log.error("Send artemis message error:{},message:{}", e, JSON.toJSONString(artemisModel.getEvent()));
            return false;
        }
        return true;
    }

    /**
     * 兼容event是String的情况
     * @param artemisModel
     * @return
     */
    public Boolean sendStringEventToArtemis(ArtemisBaseInfo artemisModel) {
        ProducerConfig producerConfig = ProducerConfig.builder().user(artemisModel.getProducer()).build();
        try {
            log.info("Send artemis message topic:{},message:{}", JSONObject.toJSONString(artemisModel.getTopic()), artemisModel.getEvent().toString());
            artemisProducer.send(producerConfig, artemisModel.getTopic(), artemisModel.getEvent().toString());
        } catch (Exception e) {
            log.error("Send artemis message error:{},message:{}", e, JSON.toJSONString(artemisModel.getEvent()));
            return false;
        }
        return true;
    }

    /**
     * 发送灰度消息
     *
     * @param artemisModel artemisModel
     * @param bosId        bosId
     * @return
     */
    @SubEnvExposePoint
    @SubEnvTagExtractor(key = "weimob-bosid", value = "#args[1]")
    public Boolean sendToArtemis(ArtemisBaseInfo artemisModel, long bosId) {
        return sendToArtemis(artemisModel);
    }

}
